<?php


namespace app\index\controller;


use app\index\common\Common;
use app\index\model\Order;
use app\index\model\OrderItem;
use app\index\model\Product;
use app\index\model\PurchaseDetail;
use app\index\model\Waybill;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
use think\Env;
use think\Image;
use think\response\Json;

class ImageController extends BaseController
{
    protected $path;
    protected $domain;
    protected $src;
    public function _initialize()
    {
        $this->path=Env::get('resource.path');
        $this->domain=Env::get('resource.image');
    }

    /**
     * 上传商品图片
     * @return Json
     */
    public function saveImage(){
        $file = request()->file('image');
        $this->src = 'yaoxing';
        $info = $file->validate(['size' => 31457280, 'ext' => 'jpg,png,jpeg'])->rule('md5')->move($this->path . $this->src);
        if ($info) {
            $saves_url = $info->getSaveName();
            $url = $this->domain . $this->src . DS . $saves_url;
            $path = $this->path . $this->src . DS . $saves_url;
            $image=Image::open($path);
            $image_info=['type'=>$image->type(),'width'=>$image->width(),'height'=>$image->height()];
            $result = $this->re_size_image($image_info,$path, 200, 200);
            if (!$result['status']) {
                return json(['code' => 1, 'msg' => $info->getFilename() . $result['msg']], 200);
            }
            $image->thumb(400,400)->save($this->path . $this->src . DS .$saves_url.'_400X400.'.$image->type());
            return json(['code' => 0, 'url' => $url, 'thump_url' => $url . $result['ext']], 200);
        }
        $error = $file->getError();
        return json(['code' => 1, 'msg' => $error], 200);
    }

    /**
     * 等比例压缩图片
     * @param $image array 图片信息
     * @param $path string 图片路径 src
     * @param $width int 要压缩到的宽
     * @param $height int 要压缩到的高
     * @return array
     */
    public function re_size_image($image,$path, $width, $height) :array
    {
        $ext = strrchr($path, '.');
        $image_src = $path;
        $thump_path = $image_src . '_' . $width . 'X' . $height . '' . $ext;

        //1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，15 = WBMP，16 = XBM
        if ($image['type'] === 'jpg' || $image['type'] === 'jpeg') {
//            $type='jpg';
            $read_function = 'imagecreatefromjpeg';
            $create_function = 'imagejpeg';
            $quantity = 85;
        } elseif ($image['type'] === 'png') {
//            $type='png';
            $read_function = 'imagecreatefrompng';
            $create_function = 'imagejpeg';
            $quantity = 85;
        } else {
            return ['status' => false, 'msg' => '图片类型错误'];
        }
        $image_info = [
            'width' => $image['width'],
            'height' => $image['height'],
        ];
        $image_resource = $read_function($image_src);
        if ($image_info['width'] > $image_info['height']) {
            $radio = $width / $image_info['width'];
            $new_width = $width;
            $new_height = $image_info['height'] * $radio;
        } else {
            $radio = $height / $image_info['height'];
            $new_width = $image_info['width'] * $radio;
            $new_height = $height;
        }
        $image_thump = imagecreatetruecolor($new_width, $new_height);
        $result = imagecopyresampled($image_thump, $image_resource, 0, 0, 0, 0, $new_width, $new_height, $image_info['width'], $image_info['height']);
        if (!$result) {
            return ["status" => false, 'msg' => '压缩图片出错_' . $width . 'X' . $height . ''];
        }
        $result = $create_function($image_thump, $thump_path, $quantity);
        if (!$result) {
            return ["status" => false, 'msg' => '压缩图片出错_' . $width . 'X' . $height . ''];
        }
        imagedestroy($image_thump);
        return ['status' => true, 'path' => $thump_path, 'ext' => '_' . $width . 'X' . $height . '' . $ext];
    }

    /**
     * BarCode
     * 商品条形码
     * @url image/barcode
     * @method POST
     * @throws \Mpdf\MpdfException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/3/16
     */
    public function BarCode()
    {
        $ids=input('get.id');
        $ids=explode(',',$ids);
        $number=input('get.number','');
        $number=$number?explode(',',$number):[];
        $codeClass=new BarcodeGenerator();;
        if(empty($ids)){
            return json(['code'=>0,'msg'=>'id 不能为空']);
        }
//        $this->src='yaoxing/barcode';

//        $id=[21,22];
        $product=Product::where('id','in',$ids)->field('id,cn_name,en_name,selling_price,type')->select()->toArray();
        $html='';
        $codeClass->setType(BarcodeGenerator::Code128);
        $codeClass->setScale(1);
        $codeClass->setThickness(20);
        $codeClass->setFontSize(8);
        $codeClass->setLabel('');
        if(empty($product)){
            return json(['code'=>0,'msg'=>'未找到商品']);
        }
        foreach ($product as $key=>$value){
            $max_id_len=strlen($value['id']);
            $bar_code_pro_id=$value['id'];
            if($max_id_len<5){
                $bar_code_pro_id=substr('00000',0,5-$max_id_len).($value['id']);
            }
            $codeClass->setText((string)$bar_code_pro_id);
            $barcode=$codeClass->generate();
            $value['cn_name']=mb_substr($value['cn_name'],0,10).'...';
            $value['type_text']='PC';
            $value['type']===2 && $value['type_text']='KG';
            $value['barcode']=$barcode;
            if(isset($number[$key]) && is_numeric($number[$key])){
                for ($i=0;$i<$number[$key];$i++) {
                    $html .= $this->barcodeHtmlPage($value);
                }
            }else{
                $html .= $this->barcodeHtmlPage($value);
            }
        }
//        echo $html;die();
        $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8', 'format'=>[40,30], 'default_font_size'=>8, 'margin_left'=>0, 'margin_right'=>0,'margin_top'=>0, 'margin_bottom'=>0]);
        $mpdf->allow_charset_conversion = true;
        $mpdf->charset_in = 'utf-8';
        $mpdf->SetTitle("Barcode");
        $mpdf->SetAuthor("YaoXing");
        $mpdf->SetCreator("YaoXing");
        $mpdf->SetSubject("Barcode");
        $mpdf->SetKeywords("Barcode");
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->WriteHTML($html);
        echo $mpdf->Output('barcode.pdf','I');
        die();
    }

    public function barcodeHtmlPage($data): string
    {
        $html='
<div style="width: 161px;height: 123px;">
<div style="height: 82px">
<table style="height: 100%;width: 100%;text-align: center;">
    <tr>
        <td colspan="3" style="font-size:10px;">
            '.$data['cn_name'].'
        </td>
    </tr>
    <tr>
        <td colspan="3" style="font-size:10px">
            '.$data['en_name'].'
        </td>
    </tr>
    <tr>
        <td style="font-size: 11px;width: 50%">
            $'.$data['selling_price'].'/'.$data['type_text'].'
        </td>
        <td style="font-size: 10px">
            
        </td>
        <td style="font-size: 10px">
            
        </td>
    </tr>
    <tr>
        <td colspan="3">
            
        </td>
    </tr>
</table>
</div>
<div style="width:99%;text-align: center;margin: 0 auto 0 auto"><img src="data:image/png;base64,'.$data['barcode'].'"></div>
<div style="font-size:8px;width:99%;text-align: center;margin: 0 auto 0 auto">'.$data['id'].'</div>
</div>';
        return $html;
    }

    public function purchaseListCode(){
        $ids=input('get.id');
        if(empty($ids)){
            return json(['code'=>0,'msg'=>'id 不能为空']);
        }
        $ids=explode(',',$ids);

        $purchase=PurchaseDetail::where('id','in',$ids)->where('del_flag',0)->field('cn_name,type,image,pur_price,amount')->select()->toArray();
        if(empty($purchase)){
            return json(['code'=>0,'msg'=>'未找到采购单']);
        }
        foreach ($purchase as $key=>$value){
            $value['total_price']=round($value['pur_price']*$value['amount'],2);
            $value['amount'] .= '/' . Product::$product_type[$value['type']];
            if($value['image']) {
                $thumb_image= Common::getThumbImage($value['image'], '_400X400');
                $thumb_image = str_replace($this->domain,$this->path,$thumb_image);
                $value['image'] = str_replace($this->domain,$this->path,$value['image']);
                if(is_file($value['image'])) {
                    if (!is_file($thumb_image)){
                        $image = Image::open($value['image']);
                        $image->thumb(400, 400)->save($thumb_image);
                        $value['image'] = $thumb_image;
                    }else {
                        $value['image'] = $thumb_image;
                    }
                }
            }
            $purchase[$key]=$value;
        }
        $html=$this->purchaseHtmlPage($purchase);
//        echo $html;die();
        $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8', 'format'=>'A4',]);
        $mpdf->allow_charset_conversion = true;
        $mpdf->charset_in = 'utf-8';
        $mpdf->SetTitle("Purchase");
        $mpdf->SetAuthor("YaoXing");
        $mpdf->SetCreator("YaoXing");
        $mpdf->SetSubject("Purchase");
        $mpdf->SetKeywords("Purchase");
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->WriteHTML($html);
        echo $mpdf->Output('purchase.pdf','I');
        die();
    }

    public function purchaseHtmlPage($purchase){
        $html='
<style>
th,td{
border-bottom: 1px solid #999;

border-right: 1px solid #999;
}
</style>

<div style="width: 100%">
<h3 style="text-align: center">采购单</h3>
    <table style="width:100%;text-align: center; border-collapse: separate;border-spacing: 0 0; border-top: 1px solid #999;border-left: 1px solid #999;">
    <tr>
    <th style="width:33%">
        品名
    </th>
    <th style="width:33%">
        图片
    </th>
    <th style="width:10%">
        单价
    </th>
    <th style="width:12%">
        数量
    </th>
    <th style="width:12%">
        总价
    </th>
    </tr>
';

        foreach ($purchase as $key=>$value){
            $image_str='';
            if($value['image']){
                $image_str='<img src="'.$value['image'].'" style="max-width: 200px;max-height:400px">';
            }
            $html.='
            <tr>
                <td>
                    '.$value['cn_name'].'
                </td>
                <td>
                    '.$image_str.'
                </td>
                <td>
                    '.$value['pur_price'].'
                </td>
                <td>
                    '.$value['amount'].'
                </td>
                <td>
                    '.$value['total_price'].'
                </td>
            </tr>
            ';
        }

        $html.='
</table>
</div>';
        return $html;
    }

    public function waybillPdf(){
        $ids=input('get.id');

        $waybill_data=Waybill::getWaybillDataForPdfByIds($ids);
        if(empty($waybill_data)){
            return json(['code'=>1,'msg'=>'未找到运单']);
        }

        $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8', 'format'=>[120,80], 'default_font_size'=>16, 'margin_left'=>0, 'margin_right'=>0,'margin_top'=>0, 'margin_bottom'=>0]);
        $mpdf->allow_charset_conversion = true;
        $mpdf->charset_in = 'utf-8';
        $mpdf->SetTitle("Waybill");
        $mpdf->SetAuthor("YaoXing");
        $mpdf->SetCreator("YaoXing");
        $mpdf->SetSubject("Waybill");
        $mpdf->SetKeywords("Waybill");
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;

        foreach ($waybill_data as $key=>$value) {
            $logo = $this->path . 'yaoxing' . DS . 'logo' . DS . $value['logo_image'];
            $mpdf->SetWatermarkImage($logo,1,[$value['width'],$value['height']],[4,3]);
            $html = $this->waybillHtmlPage($value);
            $mpdf->showWatermarkImage = true;
            $mpdf->WriteHTML($html);
            if($key===count($waybill_data)-1){
                continue;
            }
            $mpdf->AddPage();
        }


        echo $mpdf->Output('waybill.pdf','I');
        die();
    }

    public function waybillHtmlPage($data){
        $html='
<div style="width: 100%">
        <h3 style="text-align: center;margin-left: 20%;line-height:50px">NO. '.$data['ship_no'].'</h3>
    <table style="width:100%;text-align: center;">
    <tr>
        <td height="80px" style="width:40%">Name:</td>
        <td height="80px">'.$data['nick_name'].'</td>
    </tr>
    <tr>
        <td height="110px" style="width:40%">Package Weight:</td>
        <td height="110px"></td>
    </tr>
    <tr>
        <td colspan="3" style="font-size: 10px">'.$data['waybill_note'].'</td>
    </tr>
';
        $html.='
</table>
</div>';
        return $html;
    }

    public function download(){
        $url=input('get.url');
        $path=str_replace($this->domain,$this->path,$url);
        if(!is_file($path)){
            return json(['code'=>1,'msg'=>'未找到图片']);
        }
        $image = @getimagesize($path);

        $name = basename($path);
        header('Content-Type: '.$image['mime']);
        header('Content-Disposition: attachment; filename="'.$name.'"');
        header('Content-Length:' . filesize($path));
        readfile($path);
    }

    public function deCodePako($form){
        $form=str_replace(' ','+',$form);
        $data=base64_decode($form);
        $flags = ord(substr($data, 3, 1));
        $headerlen = 10;
        $extralen = 0;
        $filenamelen = 0;
        if ($flags & 4) {
            $extralen = unpack('v' ,substr($data, 10, 2));
            $extralen = $extralen[1];
            $headerlen += 2 + $extralen;
        }
        if ($flags & 8) // Filename
            $headerlen = strpos($data, chr(0), $headerlen) + 1;
        if ($flags & 16) // Comment
            $headerlen = strpos($data, chr(0), $headerlen) + 1;
        if ($flags & 2) // CRC at end of file
            $headerlen += 2;
        $unpacked = @gzinflate(substr($data, $headerlen));
        if ($unpacked === FALSE)
            $unpacked = $data;
        return $unpacked;
    }

    public function stockOurPrint(){
        $form=input('get.data');
        $form=$this->deCodePako($form);
        $form=json_decode($form,true);
        $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8', 'format'=>'A4', 'default_font_size'=>13, 'margin_left'=>5, 'margin_right'=>5,'margin_top'=>5, 'margin_bottom'=>5]);
        $mpdf->allow_charset_conversion = true;
        $mpdf->charset_in = 'utf-8';
        $mpdf->SetTitle("stock");
        $mpdf->SetAuthor("YaoXing");
        $mpdf->SetCreator("YaoXing");
        $mpdf->SetSubject("stock");
        $mpdf->SetKeywords("stock");
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;

        $html = $this->stockOutHtmlPage($form);
        $mpdf->WriteHTML($html);

        echo $mpdf->Output('stock.pdf','I');
        die();
    }

    public function stockOutHtmlPage($data){
        $item_body = '';
        $total_price=0;
        foreach ($data as $key => $value) {
            if(!is_numeric($value['amount'])){
                return $value['cn_name'].'输入的不是数字';
            }
            if(!isset($value['amount']) || !$value['amount']){
                return $value['cn_name'].'出库数量必须大于0';
            }
            if($value['type']===1){
                $isMatched=preg_match('/\D|^0/', $value['amount'], $matches);
                if($isMatched){
                    return $value['cn_name'].'输入的数字不对';
                }
            }
            $price=round($value['amount']*$value['selling_price'],2);
            $total_price+=$price;
            $item_body .= '
            <tr class="item_body">
                <td style="width: 15%">' .$value['pro_id']. '</td>
                <td style="width: 40%">' . $value['cn_name']. '</td>
                <td style="width: 10%">' . (Product::$product_type[$value['type']]). '</td>
                <td style="width: 10%">' . $value['amount']. '</td>
                <td style="width: 10%">' . $value['selling_price']. '</td>
                <td style="width: 15%">' . $price. '</td>
            </tr>';
        }

        $html='
<style>
.item_head{
font-size: 13px;
background:#8c939d
}
.item_head td{
border-left: 1px solid black;
border-top: 1px solid black;
text-align:center;
vertical-align:middle;
}
.item_body{
font-size: 13px;
}
.item_body td{
border-left: 1px solid black;
border-top: 1px solid black;
text-align:center;
vertical-align:middle;
}
</style>
    <table style="width: 100%;border-bottom: 1px solid black;border-right:1px solid black;margin-top: 10px" cellspacing="0"  cellpadding="4">
                <tr class="item_head">
                    <td>
                    <b>商品ID</b>
                    </td>
                    <td>
                    <b>商品中文名</b>
                    </td>
                    <td>
                    <b>单位</b>
                    </td>
                    <td>
                    <b>数量</b>
                    </td>
                    <td>
                    <b>单价</b>
                    </td>
                    <td>
                    <b>金额(￥)</b>
                    </td>
                </tr>
                '. $item_body . '
';
        $html.='
</table>
总计：'.$total_price.'
';
        return $html;
    }

    public function invoicePdf(){
        $id=input('get.id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'id 不能为空']);
        }

        $data=Order::where('o.id','=',$id)->where('o.del_flag',0)->alias('o')->join('country c','o.country=c.id','left')->join('customer cu','o.customer_id=cu.id','left')->field('o.order_id,cu.nick_name user_name,o.pay_type,o.total_price,o.ship_fee,o.amount_discount,o.amount_paid,c.country_name')->find();
        if(empty($data)){
            return json(['code'=>0,'msg'=>'未找到订单']);
        }
        $data['pay_type_status']=Order::$pay_type_list[$data['pay_type']];
        $order_item=OrderItem::where('oi.order_id','=',$id)->where('oi.del_flag',0)->alias('oi')->join('user u','oi.create_user=u.id','left')->field('oi.cn_name,oi.en_name,oi.amount,oi.remark,oi.selling_price,u.user_name')->select()->toArray();
        if(empty($order_item)){
            return json(['code'=>0,'msg'=>'未找到订单']);
        }
        $html=$this->invoiceHtmlPage($data,$order_item);
//        echo $html;die();
        $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8', 'format'=>'A4',]);
        $mpdf->allow_charset_conversion = true;
        $mpdf->charset_in = 'utf-8';
        $mpdf->SetTitle("Invoice");
        $mpdf->SetAuthor("YaoXing");
        $mpdf->SetCreator("YaoXing");
        $mpdf->SetSubject("Invoice");
        $mpdf->SetKeywords("Invoice");
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->WriteHTML($html);
        echo $mpdf->Output('invoice.pdf','I');
        die();
    }

    public function invoiceHtmlPage($data,$order_item){
        $item='';
        foreach ($order_item as $key=>$value){
            $item.='<tr>
                    <td style="text-align: center">'.$value['en_name'].'</td>
                    <td style="text-align: center">'.$value['cn_name'].'</td>
                    <td style="text-align: center">'.$value['amount'].'</td>
                    <td style="text-align: center">'.$value['selling_price'].'</td>
                    <td style="text-align: center">'.$value['user_name'].'</td>
                    <td style="text-align: center">'.$value['remark'].'</td>
                </tr>';
        }
        $html= '
<style>
.item td{
border-bottom: 1px solid #999;

border-right: 1px solid #999;
}
.item th{
border-bottom: 1px solid #999;

border-right: 1px solid #999;
}
</style>
        <div style="width: 100%">
            <table style="width: 100%">
                <tr>
                    <td width="50%"><span style="color: #5f5f63">&#12288;订单号: </span><span style="font-weight: bold">' .$data['order_id'].'</span></td>
                    <td><span style="color: #5f5f63">付款状态: </span><span>'.$data['pay_type_status'].'</span></td>
                </tr>
                <tr>
                    <td><span style="color: #5f5f63">&#12288;&#12288;国家: </span><span>'.$data['country_name'].'</span></td>
                    <td><span style="color: #5f5f63">&#12288;用户名: </span><span style="font-weight: bold">'.$data['user_name'].'</span></td>
                </tr>
                <tr>
                    <td><span style="color: #5f5f63">&#12288;&#12288;金额: </span><span>'.$data['total_price'].'USD / 已付'.$data['amount_paid'].'USD</span></td>
                    <td><span style="color: #5f5f63">&#12288;&#12288;折扣: </span><span>'.$data['amount_discount'].'USD</span>
                   <span style="color: #5f5f63">运费: </span><span>'.$data['ship_fee'].'USD</span></td>
                </tr>
            </table>
            <table class="item" style="width: 100%;border-collapse: separate;border-spacing: 0 0; border-top: 1px solid #999;border-left: 1px solid #999;">
                <tr>
                    <th>商品英文名</th>
                    <th>商品中文名</th>
                    <th>数量</th>
                    <th>售价</th>
                    <th></th>
                    <th>备注</th>
                </tr>
                '.$item.'
            </table>
        ';

        $html.='</div>';
        return $html;
    }
}